<template>
  <div class="params-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-alert
        show-icon
        title="必须且只能选择三级分类"
        type="warning"
        :closable="false">
      </el-alert>

      <el-row>
        <el-col class="selected-cate">
          选择分类: 
          <el-cascader
            v-model="selectedCascader"
            :options="cateList"
            :props="cascaderProps"
            @change="selectedCascaderChange"
            clearable>
          </el-cascader>
        </el-col>
      </el-row> 

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态属性" name="many">
          <el-row>
            <el-col>
              <el-button type="primary" :disabled="isAddCate" @click="showAddDialog">添加参数</el-button>
            </el-col>
          </el-row>

          <el-table
            v-show="manyTabList.length"
            border
            :data="manyTabList"
            style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="closeAttrVal(scope.row, index)">
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#">
            </el-table-column>
            <el-table-column
              label="属性"
              prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="showEditDialog(scope.row)">
                  编辑
                </el-button>
                <el-button size="mini" type="danger" @click="deleteAttr(scope.row.attr_id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only"> 
          <el-row>
            <el-col>
              <el-button type="primary" :disabled="isAddCate" @click="showAddDialog">添加参数</el-button>
            </el-col>
          </el-row>

          <el-table
            v-show="onlyTabList.length"
            border
            :data="onlyTabList"
            style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="closeAttrVal(scope.row, index)">
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#">
            </el-table-column>
            <el-table-column
              label="属性"
              prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="showEditDialog(scope.row)">
                  编辑
                </el-button>
                <el-button size="mini" type="danger"  @click="deleteAttr(scope.row.attr_id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs> 
    </el-card>

    <el-dialog
      :title="'添加' + titleLabel"
      @close="closeAddDialogVisible"
      :visible.sync="addDialogVisible"
      width="50%">
      <el-form :model="addRuleForm" :rules="addrules" ref="addRuleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="属性名称" prop="attr_name">
          <el-input v-model="addRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRuleForm">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="'编辑' + titleLabel"
      @close="closeEditDialogVisible"
      :visible.sync="editDialogVisible"
      width="50%">
      <el-form :model="editRuleForm" :rules="editrules" ref="editRuleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="属性名称" prop="attr_name">
          <el-input v-model="editRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditRuleForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      selectedCascader: [],
      cascaderProps:{
        value: 'cat_id',
        label: 'cat_name',
        expandTrigger: 'hover' 
      },
      id: '',
      activeName: 'many',
      manyTabList: [],
      onlyTabList: [],
      addDialogVisible: false,
      addRuleForm: {
        attr_name: ''
      },
      addrules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editRuleForm: {
        attr_name: '',
        attr_id: ''
      },
      editrules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const {data: res} = await this.$http.get('categories')
      if(res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.cateList = res.data
    },
    selectedCascaderChange() {
      if(this.selectedCascader.length !== 3) {
        this.$message.warning('只能选择第三层分类')
        this.selectedCascader = []
        this.manyTabList = []
        this.onlyTabList = []
        return 
      }
      this.getParamsList()
    },
    handleClick() {
      if(this.selectedCascader.length !== 3) {
        this.manyTabList = []
        this.onlyTabList = []
        return 
      }
      this.getParamsList()
    },
    async getParamsList() {
      const id = this.selectedCascader[2]
      this.id = this.selectedCascader[2]

      const {data: res} = await this.$http.get(`categories/${id}/attributes`, {params: {sel: this.activeName}})
      
      if(res.meta.status !== 200) {
        return this.$$message.error(res.meta.msg)
      }

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals !== '' && item.attr_vals.split(',')
        item.inputVisible = false
        item.inputValue = ''
      })
  
      if( this.activeName === 'many') {
        this.manyTabList = res.data
      } else {
        this.onlyTabList = res.data
      }
    },
    showAddDialog() {
      this.addDialogVisible = true
    },
    closeAddDialogVisible() {
      this.$refs.addRuleForm.resetFields()
    },
    submitAddRuleForm() {
      this.$refs.addRuleForm.validate(async valid => {
        if (!valid) {
          this.$message.error('请填写完成信息')
          return false
        } 

        const {data: res} = await this.$http.post(`categories/${this.id}/attributes`, {
          attr_name: this.addRuleForm.attr_name,
          attr_sel: this.activeName
        })

        if(res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }

        this.$message.success(res.meta.msg)
        this.getParamsList()
        this.addDialogVisible = false
      })
    },
    showEditDialog(row) {
      this.editRuleForm.attr_name = row.attr_name
      this.editRuleForm.attr_id = row.attr_id

      this.editDialogVisible = true
    },
    closeEditDialogVisible() {
      this.$refs.editRuleForm.resetFields()
    },
    submitEditRuleForm() {
      this.$refs.editRuleForm.validate(async valid => {
        if (!valid) {
          this.$message.error('请填写完成信息')
          return false
        } 

        const {data: res} = await this.$http.put(`categories/${this.id}/attributes/${this.editRuleForm.attr_id}`, {
          attr_name: this.editRuleForm.attr_name,
          attr_sel: this.activeName
        })

        if(res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        
        this.getParamsList()
        this.editDialogVisible = false
      })
    },
    deleteAttr(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data: res} = await this.$http.delete(`categories/${this.id}/attributes/${id}`)

        if(res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }

        this.$message.success(res.meta.msg)
        this.getParamsList()

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })       
      })
    },
    async closeAttrVal(row, index) {
      row.attr_vals.splice(index, 1)

      const {data: res} = await this.$http.put(`categories/${this.id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(',')
      })

      if(res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.$message.success(res.meta.msg)
    },
    handleClose() {
      
    },
    showInput(row) {
      row.inputVisible = true

      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async handleInputConfirm(row) {
      if(row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return false
      }

      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      
      const {data: res} = await this.$http.put(`categories/${this.id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(',')
      })

      if(res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.$message.success(res.meta.msg)
    }
  },
  computed: {
    isAddCate() {
      return this.selectedCascader.length === 3 ? false : true
    },
    titleLabel() {
      if(this.activeName === 'many') {
        return '动态属性'
      }

      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.params-container {
  .box-card {
    margin: 20px 0;
  }
  .selected-cate{
    margin: 20px 0;
  }
  .el-cascader{
    width: 300px;
  }
  .el-table {
    margin: 20px 0;
  }
  .el-tag {
    margin: 8px;
    cursor: pointer;
    user-select: none;
  }
  .el-input {
    width: 150px;
  }
}
</style>
